<template>
  <el-dialog
    v-model="visible"
    title="用户详情"
    width="600px"
    :before-close="handleClose"
  >
    <div v-loading="loading">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户ID">{{ userDetail.id }}</el-descriptions-item>
        <!-- <el-descriptions-item label="用户名">{{ userDetail.username }}</el-descriptions-item> -->
        <el-descriptions-item label="昵称">{{ userDetail.nickname }}</el-descriptions-item>
        <!-- <el-descriptions-item label="邮箱">{{ userDetail.email }}</el-descriptions-item> -->
        <el-descriptions-item label="手机号">{{ userDetail.phone }}</el-descriptions-item>
        <!-- <el-descriptions-item label="角色">
          <el-tag v-for="role in userDetail.roles" :key="role" style="margin-right: 5px;">
            {{ role }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="权限">
          <el-tag v-for="permission in userDetail.permissions" :key="permission" style="margin-right: 5px;">
            {{ permission }}
          </el-tag>
        </el-descriptions-item> -->
        <!-- <el-descriptions-item label="状态">
          <el-tag :type="userDetail.status === 'active' ? 'success' : 'danger'">
            {{ userDetail.status === 'active' ? '活跃' : '禁用' }}
          </el-tag>
        </el-descriptions-item> -->
        <el-descriptions-item label="创建时间">{{ formatDate(userDetail.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ formatDate(userDetail.last_login) }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 治疗记录 -->
      <el-card v-if="treatmentRecords.length > 0" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>最近治疗记录</span>
            <el-button type="primary" size="small" @click="openRemoteConfig">远程配置治疗方案</el-button>
          </div>
        </template>
        <el-table :data="treatmentRecords" style="width: 100%">
          <el-table-column prop="device_id" label="设备ID" width="120" />
          <el-table-column prop="mode" label="治疗模式" width="100" />
          <el-table-column prop="start_time" label="开始时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.start_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="持续时间" width="100">
            <template #default="{ row }">
              {{ formatDuration(row.duration) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 'completed' ? 'success' : 'warning'">
                {{ row.status === 'completed' ? '已完成' : '进行中' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 远程配置对话框 -->
      <el-dialog
        v-model="remoteConfigVisible"
        title="远程配置治疗方案"
        width="500px"
      >
        <el-form :model="remoteConfigForm" label-width="100px">
          <el-form-item label="模板名称" prop="template_name" :rules="[{ required: true, message: '请输入模板名称', trigger: 'blur' }]">
            <el-input v-model="remoteConfigForm.template_name" placeholder="请输入模板名称" />
          </el-form-item>
          <el-form-item label="模板类型">
            <el-select v-model="remoteConfigForm.template_type" placeholder="请选择模板类型">
              <el-option label="医院" value="hospital" />
              <el-option label="学校" value="school" />
              <el-option label="企业" value="enterprise" />
              <el-option label="科研" value="research" />
            </el-select>
          </el-form-item>
          <el-form-item label="治疗模式">
            <el-select v-model="remoteConfigForm.mode" placeholder="请选择治疗模式">
              <el-option label="tDCS+" value="tDCS+" />
              <el-option label="tDCS-" value="tDCS-" />
              <el-option label="tACS" value="tACS" />
            </el-select>
          </el-form-item>
          <el-form-item label="电流强度(mA)">
            <el-slider 
              v-model="remoteConfigForm.current" 
              :min="0" 
              :max="2" 
              :step="0.01"
              show-input
            />
          </el-form-item>
          <el-form-item label="治疗时间(分钟)">
            <el-input-number 
              v-model="remoteConfigForm.duration" 
              :min="1" 
              :max="60" 
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="频率(Hz)" v-if="remoteConfigForm.mode === 'tACS'">
            <el-input-number 
              v-model="remoteConfigForm.frequency" 
              :min="0.1" 
              :max="100" 
              :step="0.1"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="设为默认">
            <el-switch v-model="remoteConfigForm.is_default" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input 
              v-model="remoteConfigForm.remark" 
              type="textarea" 
              placeholder="请输入配置备注"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="remoteConfigVisible = false">取消</el-button>
            <el-button type="primary" @click="sendRemoteConfig">发送配置</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserDetail } from '@/api/user'
import { createRemoteTreatmentTemplate } from '@/api/user'
import { formatDate, formatDuration } from '@/utils/format'

interface User {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  roles: string[]
  permissions: string[]
  status: string
  created_at: string
  last_login: string
}

interface TreatmentRecord {
  id: string
  device_id: string
  mode: string
  start_time: string
  duration: number
  status: string
}

interface Props {
  modelValue: boolean
  user: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
  (e: 'edit', user: User): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const loading = ref(false)
const remoteConfigVisible = ref(false)
const userDetail = ref<User>({
  id: 0,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  roles: [],
  permissions: [],
  status: 'active',
  created_at: '',
  last_login: ''
})
const treatmentRecords = ref<TreatmentRecord[]>([])

const remoteConfigForm = ref({
  template_name: '',
  template_type: 'hospital',
  mode: 'tDCS+',
  current: 1.0,
  duration: 20,
  frequency: 10.0,
  is_default: false,
  remark: ''
})

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val && props.user) {
    loadUserDetail(props.user.id)
  }
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    // 重置数据
    userDetail.value = {
      id: 0,
      username: '',
      nickname: '',
      email: '',
      phone: '',
      roles: [],
      permissions: [],
      status: 'active',
      created_at: '',
      last_login: ''
    }
    treatmentRecords.value = []
  }
})

// 监听治疗模式变化
watch(() => remoteConfigForm.value.mode, (newMode) => {
  if (newMode !== 'tACS') {
    remoteConfigForm.value.frequency = 0
  } else if (!remoteConfigForm.value.frequency) {
    remoteConfigForm.value.frequency = 10.0
  }
})

const loadUserDetail = async (userId: number) => {
  if (!userId) return
  
  loading.value = true
  try {
    const response: any = await getUserDetail(userId.toString())
    userDetail.value = { ...userDetail.value, ...response.data }
    // 这里应该从API获取治疗记录，暂时用模拟数据
    treatmentRecords.value = [
      {
        id: '1',
        device_id: 'DEV001',
        mode: 'tDCS+',
        start_time: '2023-05-15T10:30:00Z',
        duration: 1800,
        status: 'completed'
      }
    ]
  } catch (error) {
    ElMessage.error('获取用户详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  visible.value = false
}

const handleEdit = () => {
  emit('edit', userDetail.value)
  visible.value = false
}

const openRemoteConfig = () => {
  // 重置表单
  remoteConfigForm.value = {
    template_name: '',
    template_type: 'hospital',
    mode: 'tDCS+',
    current: 1.0,
    duration: 20,
    frequency: 10.0,
    is_default: false,
    remark: ''
  }
  remoteConfigVisible.value = true
}

const sendRemoteConfig = async () => {
  try {
    // 验证表单
    if (!remoteConfigForm.value.template_name) {
      ElMessage.error('请输入模板名称')
      return
    }
    
    // 构造发送到后端的数据
    const configData = {
      user_id: userDetail.value.id,
      template_name: remoteConfigForm.value.template_name,
      template_type: remoteConfigForm.value.template_type,
      treatment_mode: remoteConfigForm.value.mode,
      current_intensity: remoteConfigForm.value.current,
      treatment_duration: remoteConfigForm.value.duration,
      frequency: remoteConfigForm.value.mode === 'tACS' ? remoteConfigForm.value.frequency : 0,
      is_default: remoteConfigForm.value.is_default,
      remark: remoteConfigForm.value.remark
    }
    
    // 调用API发送远程配置
    await createRemoteTreatmentTemplate(configData)
    
    ElMessage.success('远程治疗方案配置成功')
    remoteConfigVisible.value = false
  } catch (error) {
    ElMessage.error('发送远程配置失败: ' + (error as any).message || '')
    console.error(error)
  }
}
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>